package cn.touna.jss.modules.callback.controller;

import cn.touna.jss.common.entity.CreditQueryRequest;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.mq.KafkaComponent;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 公信宝回调
 */
@RestController
public class GxbCallbackController {

    @Autowired
    private KafkaComponent kafkaComponent;

    @PostMapping("/gxb/pushRawdata")
    public String pushRawdata(@RequestBody String body){
        JSONObject result = new JSONObject();
        try{
            JSONObject request = JSONObject.parseObject(body);
            Response response = transfer(request);

            CreditQueryRequest queryRequest = new CreditQueryRequest();
            queryRequest.setCrNo(request.getString("sequenceNo"));
            queryRequest.setMobile(request.getString("phone"));
            queryRequest.setIdCard(request.getString("idcard"));
            //结果推送给变量系统
            kafkaComponent.sendSyncCallData(queryRequest, response);
        }catch (Exception e){
            result.put("retCode",2);
            result.put("retMsg","失败");
            return result.toJSONString();
        }

        result.put("retCode",1);
        result.put("retMsg","成功");
        return result.toJSONString();
    }

    /**
     * 转换结果
     * @param res
     * @return
     */
    private Response transfer(JSONObject res){
        JSONObject authInfoVo = new JSONObject();
        copy(res,authInfoVo,"authItem");
        copy(res,authInfoVo,"idcard");
        copy(res,authInfoVo,"phone");
        copy(res,authInfoVo,"token");
        copy(res,authInfoVo,"sequenceNo");


        JSONObject data = new JSONObject();
        data.put("authInfoVo",authInfoVo);
        data.put("authResult",res.getJSONObject("authJson"));

        JSONObject result = new JSONObject();
        result.put("retCode",1);
        result.put("retMsg","成功");

        return ResponseFactory.success(result);
    }

    private void copy(JSONObject source,JSONObject target,String field){
        copy(source,target,field,field);
    }
    private void copy(JSONObject source,JSONObject target,String srcField,String tgtField){
        target.put(tgtField,source.get(srcField));
    }
}
